<?php
/**
 * Akimimi front
 * UserPointService
 * by M.Wang
 */

require_once ('../app/core/services/BaseService.php');
require_once ('../app/constants/UserConstants.php');
require_once '../app/models/UserPointLogDao.php';

class UserPointService extends BaseService{
    /**
     * @var UserDao
     */
    private $userDao;

    /**
     * @var UserPointLogDao
     */
    private $userPointLogDao;

    public function __construct($components = array()){
        parent::__construct($components);
        $this->userDao = new UserDao($this->dbUtil);
        $this->userPointLogDao = new UserPointLogDao($this->dbUtil);
    }

    /**
     * @param int $int_id users.id
     * @return array
     */
    protected function getUserInfoById($int_id){
        return $this->userDao->getCustomerById($int_id);
    }

    /**
     * 更新用户积分
     *
     * @param int $int_userid users.id
     * @param int $int_offset 增加为正数，减少为负数
     * @param int $int_type 积分类型[1-注册，2-咨询，3-评论，4-交易成功，5-兑换]
     * @param string $str_description 备注信息。如： 订单A00356交易成功。
     * @param boolean $bool_buyer 默认为买家积分。暂时不支持卖家积分
     * @return int|false 成功则返回更新后的积分
     */
    public function updatePoint($int_userid, $int_offset, $int_type, $str_description='', $bool_buyer = true){
        require_once '../app/constants/UserConstants.php';
    	$int_stablePoint = UserConstants::getStablePointNumberByKey($int_type);
        if($int_stablePoint)
            $int_offset = $int_stablePoint;
        /**
         * 当$int_type=2时检查日咨询积分情况
         */
        if($int_type==2){
            $int_todayQueryPoint = $this->userPointLogDao->getUserTodayQueriesPoints($int_userid);
            if( $int_todayQueryPoint > ( 5 - 1 ) * UserConstants::getStablePointNumberByKey($int_type) )
                return true;
        }
        /**
         * 当$int_type=3时检查日评论积分情况
         */
        if($int_type==3){
//            $int_todayCommentsPoint = $this->userPointLogDao->getUserTodayCommentsPoints($int_userid);
//            if( $int_todayCommentsPoint > ( 5 - 1 ) * UserConstants::getStablePointNumberByKey($int_type) )
//                return true;
        }
        $arr_users = $this->getUserInfoById($int_userid);
        $arr_user = $arr_users[0];
        $str_column = 'points_buyer';
        $str_column_total = 'points_buyer_total';
        if( !$bool_buyer ){
            $str_column = 'points_seller';
            $str_column_total = 'points_seller_total';
        }
        
        /**
         * base on the points_seller_total point to judge if upgrade the rank
         */
//        $int_nowPoint = intval($arr_user[$str_column], 10) + $int_offset;//by w.m
        $int_nowPoint = intval($arr_user[$str_column], 10) + $int_offset;//by g.c
        $int_nowPoint_total = intval($arr_user[$str_column_total], 10) + $int_offset;//by g.c
        
        /**
         * update the point number
         */
//        $arr_map = array($str_column => $int_nowPoint);//by w.m
        $arr_map = array( $str_column => $int_nowPoint, $str_column_total => $int_nowPoint_total );//by g.c

        /**
         * if is buyer, update user rank setting
         */
        if( $bool_buyer )
            $arr_map['rank'] = $this->getUserRank( $int_nowPoint_total );

        if( !$this->userDao->update($arr_map, " id={$int_userid}") )
            return false;

        /**
         * if is buyer, insert record into user_point_logs
         */
        if( $bool_buyer ){
            $arr_param = array(
                'user_id' => $int_userid,
                'type' => $int_type,
                'point' => $int_offset,
                'current_point' => $int_nowPoint,
                'description' => $str_description,
                'created' => date('Y-m-d H:i:s')
            );
            if( $this->insertUserPointLog($arr_param) )
                return $int_nowPoint;
            else
                return false;
        }
        return $int_nowPoint;
    }

    /**
     * Count user rank by point
     */
    protected function getUserRank($int_point){
        $int_rank=1;
        if( $int_point >= 1000 )
            $int_rank++;
        if( $int_point >= 4000 )
            $int_rank++;
        if( $int_point >= 10000 )
            $int_rank++;
        if( $int_point >= 30000 )
            $int_rank++;
        if( $int_point >= 50000 )
            $int_rank++;
        return $int_rank;
    }

    /**
     * insert into user_point_logs
     */
    protected function insertUserPointLog($arr_map){
        return $this->userPointLogDao->insert($arr_map);
    }

    /**
     * Update buyer's point
     *
     * @param int $int_id users.id
     * @param int $int_offset point offset
     * @return int|false
     */
    protected function updateBuyerPoint($int_id, $int_offset){
        return $this->updatePoint($int_id, $int_offset);
    }

    /**
     * Update seller's point
     *
     * @param int $int_id users.id
     * @param int $int_offset point offset
     * @return int|false
     */
    protected function updateSellerPoint($int_id, $int_offset){
        return $this->updatePoint($int_id, $int_offset, false);
    }

    /**
     * get user point update logs
     */
    public function getUserPointLogs($int_userid, $int_page, $int_limit){
        $arr_logs = $this->userPointLogDao->getLogsByUserId($int_userid, $int_page, $int_limit);
        if( empty( $arr_logs ) )
            return array();
        $arr_logs['Count'] = $this->dbUtil->getLastFoundRows();
        $arr_logs['Count'] = $arr_logs['Count'][0]['ROWS'];
        return $arr_logs;
    }
    
    /**
     * get user today points
     */
    public function getUserTodayPoints( $int_userid, $int_type ){
    	return $this->userPointLogDao->getUserTodayPoints( $int_userid, $int_type );
    }
    
    /**
     * get the user point to transform the money
     * 可兑换积分满100，可兑换优惠券1元；$int_point_type=1
	 * 可兑换积分满500，可兑换优惠券6元；$int_point_type=2
	 * 可兑换积分满1,000，可兑换优惠券13元；$int_point_type=3
	 * 可兑换积分满1,500，可兑换优惠券20元；$int_point_type=4
	 * 可兑换积分满2,000，可兑换优惠券28元。$int_point_type=5
     */
    public function convertMoney( $int_userid, $int_point_type ){
    	$userPointInfos = $this->userDao->getUserById($int_userid);
    	$userPointInfo = $userPointInfos[0];
    	$pointBuyer = $userPointInfo["points_buyer"];
    	if($int_point_type == 1 && $pointBuyer >= 100){
        	$money = 1;
        	$point = 100;
        }elseif($int_point_type == 2 && $pointBuyer >= 500){
        	$money = 6;
            $point = 500;
        }elseif($int_point_type == 3 && $pointBuyer >= 1000){
            $money = 13;
            $point = 1000;
        }elseif($int_point_type == 4 && $pointBuyer >= 1500){
            $money = 20;
            $point = 1500;
        }elseif($int_point_type == 5 && $pointBuyer >= 2000){
            $money = 28;
            $point = 2000;
        }else{
        	$money = 0;//元
            $point = 0;
        }
    	$newPointBuyer = $pointBuyer - $point;
    	$this->userDao->update(array("points_buyer" => $newPointBuyer), " id={$int_userid}");
    	
    
        /**
         * if is buyer, insert record into user_point_logs
         */
    	$int_type = 5;
        $arr_users = $this->getUserInfoById($int_userid);
        $arr_user = $arr_users[0];
        $int_nowPoint = intval($arr_user["points_buyer_total"]) - $userPointLog;
        $str_description = "";
        
        $arr_param = array(
            'user_id' => $int_userid,
            'type' => $int_type,
            'point' => $userPointLog,
            'current_point' => $int_nowPoint,
            'description' => $str_description,
            'created' => date('Y-m-d H:i:s')
        );
        $this->insertUserPointLog($arr_param);
    	
    	return $money;
    }
    /*
    public function convertMoney( $int_userid, $int_point=0 ){
    	$userPointInfos = $this->userDao->getUserById($int_userid);
    	$userPointInfo = $userPointInfos[0];
    	$points_buyer = $userPointInfo["points_buyer"];
    	if( $points_buyer < 100 ){//如果积分小于100则不进行兑换
    	   return 0;
    	}
        if( empty($int_point) ){//用户将所有积分都转换成钱
            $pointBuyer = $points_buyer;
        }else{//将用户指定的分数转换成相应钱数
	        if( $int_point > $points_buyer ){
	            $pointBuyer = $points_buyer;
	        }else{
	            $pointBuyer = $int_point;
	        }
        }
        //$userPointLog保存到日志表中分数
        //$pointBuyer根据分数不同兑换不同钱数，只是兑换钱数时使用
        $userPointLog = $pointBuyer;
        $money = 0;
        if( $pointBuyer >= 500 && $pointBuyer < 1000 ){
        	$money += 6;
        	$pointBuyer -= 500;
        }elseif( $pointBuyer >= 1000 && $pointBuyer < 1500 ){
        	$money += 13;
            $pointBuyer -= 1000;
        }elseif( $pointBuyer >= 1500 && $pointBuyer < 2000 ){
        	$money += 20;
            $pointBuyer -= 1500;
        }elseif( $pointBuyer >= 2000 ){
        	$money += 28;
            $pointBuyer -= 2000;
        }
        
    	$money += intval( $pointBuyer / 10 ) / 10;//换成单位：元
//    	$newPointBuyer = $points_buyer - intval( $pointBuyer / 10 ) * 10;
    	$newPointBuyer = $points_buyer - intval( $userPointLog / 10 ) * 10;
    	$this->userDao->update(array("points_buyer" => $newPointBuyer), " id={$int_userid}");
    	
    
        //if is buyer, insert record into user_point_logs
    	$int_type = 5;
        $arr_users = $this->getUserInfoById($int_userid);
        $arr_user = $arr_users[0];
        $int_nowPoint = intval($arr_user["points_buyer_total"]) - $userPointLog;
        $str_description = "";
        
        $arr_param = array(
            'user_id' => $int_userid,
            'type' => $int_type,
            'point' => $userPointLog,
            'current_point' => $int_nowPoint,
            'description' => $str_description,
            'created' => date('Y-m-d H:i:s')
        );
        $this->insertUserPointLog($arr_param);
    	
    	return $money;
    }
    */

}

?>
